#coding:utf-8
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from datetime import datetime, date, timedelta
import redis
import time
import json
import re
import sys
import os

reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from config.tdm_config import *
from utils import *
import config.tdm_mongo_modules as tmm


'''
------------------------------------------------------------------------------
[JSON] get city response
------------------------------------------------------------------------------
'''
def view_get_json_city(request):
    city_list = []
    tmm.db_connect(tdm_mongo_acard_db)
    city_all = tmm.City.objects().order_by('zipcode')
    for city in city_all:
        city_list.append(city.name)
    return HttpResponse(json.dumps(city_list, ensure_ascii=False), content_type='application/javascript')

'''
------------------------------------------------------------------------------
[JSON] get jxd response by city
------------------------------------------------------------------------------
'''
def view_get_json_venue(request, city):
    venue_list = []
    city = city.encode('utf-8')
    tmm.db_connect(tdm_mongo_acard_db)
    city_obj = tmm.City.objects(name=city).first()
    if city_obj:
        for venue in city_obj.venues:
            if venue.disabled:
                continue
            venue_list.append(venue.name)
    return HttpResponse(json.dumps(venue_list, ensure_ascii=False), content_type='application/javascript')


'''
------------------------------------------------------------------------------
[JSON] get acard venue_ctmdev latest info list
------------------------------------------------------------------------------
'''
def view_get_json_acard_venuesynclog_info(request, city):
    view_venue_ctmdev_list = []
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    tmm.db_connect(tdm_mongo_acard_db)

    city = city.encode('utf-8')
    city_obj = tmm.City.objects(name=city).first()
    for venue in city_obj.venues:
        if venue.disabled:
            continue
        for ctmdev in venue.ctm_devs:
            key = '%s:%s:%s:%s' % (redis_venue_sync_log_prefix, city_obj.name, venue.name, ctmdev.devid)
            val = r.get(key)
            key_list = ('_prefix', 'city', 'venue', 'ctmdev', 'date')
            venue_log = {}
            if val:
                #print [val]
                venue_log.update(json.loads(val))
            venue_log.update(dict(zip(key_list, key.split(':'))))
            view_venue_ctmdev_list.append(venue_log)
    return HttpResponse(json.dumps(view_venue_ctmdev_list, ensure_ascii=False), content_type='application/javascript')

def view_get_json_acard_ctmdevlog_info(request, city, venue, ctmdev):
    tmm.db_connect(tdm_mongo_acard_db)
    ctmdev = ctmdev.encode('utf-8')
    ctmobj = tmm.CtmDevice.objects(devid=ctmdev).first()
    venue_log = tmm.AcardCtmLog.objects(ctm=ctmobj, log_tm__gte=(date.today()-timedelta(14)))
    return HttpResponse(venue_log.to_json(), content_type='application/javascript')

def view_get_json_report_ctm_error(request, city, start_date, end_date):
    tmm.db_connect(tdm_mongo_acard_db)
    view_city = tmm.City.objects(name=city).first()
    venue_report_list = []
    start_date = datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.strptime(end_date, '%Y-%m-%d')
    for venue in view_city.venues:
        if venue.disabled:
            continue
        pipeline = [
                {"$match": {"venue": venue.id, "log_tm":{"$gt": start_date, "$lt": end_date}}},
                {"$group": {"_id": "$status", "total": {"$sum": 1}}}
                ]
        ret = tmm.AcardCtmLog._get_collection().aggregate(pipeline)
        # {u'ok': 1.0, u'result': [{u'total': 1342, u'_id': False}, {u'total': 575, u'_id': True}]}
        ret_true = ret_false = 0
        for ret_dict in ret.get('result'):
            if ret_dict.get('_id') == False:
                ret_false = ret_dict.get('total')
            if ret_dict.get('_id') == True:
                ret_true = ret_dict.get('total')
        #print city.name, venue.name, 'ret_true:', ret_true, 'ret_false:', ret_false
        _vn_rep = {
            'vn_id': str(venue.id),
            'vn_name': venue.name,
            'rep_true': ret_true,
            'rep_false': 1 if ret_true == 0 and ret_false == 0 else ret_false
        }
        venue_report_list.append(_vn_rep)
    return HttpResponse(json.dumps(venue_report_list, ensure_ascii=False), content_type='application/javascript')

def view_get_json_report_credit_card(request, city, start_date, end_date):
    tmm.db_connect(tdm_mongo_acard_db)
    view_city = tmm.City.objects(name=city).first()
    venue_report_list = []
    start_date = datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.strptime(end_date, '%Y-%m-%d')
    for venue in view_city.venues:
        if venue.disabled:
            continue
        credit_card_list = tmm.AttendTurnoutLog.objects(city=view_city, venue=venue, date__gte=start_date, date__lte=end_date)
        _vn_rep = {
            'vn_id': str(venue.id),
            'vn_name': venue.name,
            'vn_toattend': 0,
            'vn_attend': 0
        }
        for _cr in credit_card_list:
            if _cr.ctm.devid.find('_dm_') > 0:
                _vn_rep['vn_toattend'] += _cr.toattend
            _vn_rep['vn_attend'] += _cr.attend
        venue_report_list.append(_vn_rep)
    return HttpResponse(json.dumps(venue_report_list, ensure_ascii=False), content_type='application/javascript')

def view_get_json_ctm_client(request):
    ret = {}
    ret['version'] = '2.5'
    ret['url'] = r'http://115.182.69.8/download/attend_ctm_software/acard_client.zip'
    ret['success'] = True
    ret['msg'] = ''
    return HttpResponse(json.dumps(ret, ensure_ascii=False), content_type='application/javascript')

def view_get_json_ams_client_ver(request):
    '''
    {
        "success": true,
        "message": "操作成功",
        "data": {
            "versionNo": "1.1",
            "versionPath": "/static/download/versions/venue_machine_update.zip"
        }
    }
    '''
    ret = {}
    ret['success'] = True
    ret['message'] = 'ok'
    ret['data'] = {
        'versionNo': '1.0',
        'versionPath': r'http://115.182.69.8/download/attend_ctm_software/update/ams-client.zip'
    }
    return HttpResponse(json.dumps(ret, ensure_ascii=False), content_type='application/javascript')